# -*- coding: utf-8 -*-
# @Time    : 2019/10/24 9:34
# @Author  : Damn7Kx
# @Software: PyCharm
import datetime
import hashlib
import math
import re
import hmac
import base64
from hashlib import sha256,sha512


class Get_weiboID():
    str62keys = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

    def mid2id(self, murl):

        length = len(murl)
        mid = ''
        group = int(length / 4)  # 整除4,每4位生成一组
        last_count = length % 4  # 除余4,如果有多余的单独进行计算
        for loop in range(group):  # 使用for循环进行切片每次切4位
            offset1 = length - (loop + 1) * 4
            end_offset = length - loop * 4
            value = self.str62_to10(murl[offset1:end_offset])  # 将这四位对其62转换处理
            if offset1 > 0:  # 如果offset1大于0说明还有其他的未处理 如果长度小于7就补零
                if len(value) < 7:
                    value = '0' + value
            mid = value + mid
        if last_count:  # 处理剩余的1位
            value = self.str62_to10(murl[:length - group * 4])  # 切片处理从开始到余数的位置进行62位转换
            mid = value + mid
        return mid

    def str62_to10(self, strs):
        length = len(strs)
        i10 = 0
        for s in strs:  # 循环处理每一个字符 第一个字符的3次幂,第二个字符的2次幂,第三个字符的1次幂,第四个的0次幂
            length -= 1
            i10 += int(self.str62keys.index(s) * math.pow(62, length))
        return str(i10)

    def get_bid(self, url):
        try:
            bid = url[url.rindex('/') + 1:url.index('?')]
        except:
            bid = url[url.rindex('/') + 1:]
            if "#" in bid:
                re_bid = bid.split('#')[0]
                # print("re_bid",re_bid)
                bid = re_bid
        return bid

    def run(self, url):
        try:
            bid = self.get_bid(url)
            midd = self.mid2id(bid)
            return midd
        except Exception as e:
            print(e)


class Utils(object):

    @classmethod
    def url_hash(cls, url):
        md = hashlib.md5()
        md.update(url.replace("http://", "").replace("https://", "").encode('utf-8'))
        m = md.digest()
        hash = str(base64.b64encode(m), 'utf-8').replace("/", "").replace("+", "").replace("=", "")
        return hash

    @classmethod
    def md5_encrypt(cls, chart):
        md = hashlib.md5(chart.encode())
        return md.hexdigest()

    @classmethod
    # 传入html即可
    def extract_pubtime(cls, div_text):
        pubtime = ''
        pubtime = re.search(
            r'(\d{4}\s*[年\-:/]\s*)\d{1,2}\s*[月\-：/]\s*\d{1,2}\s*[\-_:日]?\s*\d{1,2}\s*:\s*\d{1,2}\s*(:\s*\d{1,2})?',
            div_text, flags=re.S | re.I)
        if pubtime:
            pubtime = pubtime.group()
        if not pubtime:
            pubtime = re.search(r'(\d{4}\s*[年\-:/]\s*)\d{1,2}\s*[月\-：/]\s*\d{1,2}\s*[\-_:日/]?', div_text,
                                flags=re.S)
            if pubtime:
                pubtime = pubtime.group()
        if pubtime:
            pubtime = pubtime.strip()
            pubtime = pubtime.replace('年', '-').replace('月', '-').replace('日', ' ').replace('/', '-')
            pubtime = cls.drop_mutil_blank(pubtime)
            return pubtime
        else:
            return pubtime

    @classmethod
    def drop_mutil_blank(cls, str):
        str = re.sub(r'\s{2,}', ' ', str)
        return str

    # 提取作者信息
    @classmethod
    def extract_author(cls, text):
        pattern = re.compile('[\s\S]+[作者|编辑|记者|责编|来源][:|：].*?([\S\s][\u4E00-\u9FA5]+)', re.S)
        match_re = re.search(pattern, text)
        return match_re.group(1)

    @classmethod
    def process_timestamp(cls, timestamp):
        try:
            result_ = datetime.datetime.fromtimestamp(int(timestamp))
        except:
            result_ = datetime.datetime.fromtimestamp(int(timestamp) / 1000)
        result = result_.strftime("%Y-%m-%d %H:%M:%S")
        return result

    @classmethod
    def _sha256(cls, text):
        return hashlib.sha256(text.encode()).hexdigest()

    @classmethod
    def _sha1(cls, text):
        return hashlib.sha1(text.encode()).hexdigest()

    @classmethod
    def hmac_sha256(cls, plaintText, secret) -> str:
        '''
        :param plaintText: 加密文本
        :param secret: 盐值
        :return:
        '''
        data = plaintText.encode('utf-8')  # 加密数据
        appsecret = secret.encode('utf-8')  # 加密数据
        signature = base64.b64encode(hmac.new(appsecret, data, digestmod=sha256).digest())
        return signature.decode()

    @classmethod
    def hmac_sha512(cls, plaintText, secret) -> str:
        '''
        :param plaintText: 加密文本
        :param secret: 盐值
        :return:
        '''
        data = plaintText.encode('utf-8')  # 加密数据
        appsecret = secret.encode('utf-8')  # 加密数据
        signature = base64.b64encode(hmac.new(appsecret, data, digestmod=sha512).digest())
        return signature.decode()




if __name__ == '__main__':
    # a = "https://weibo.com/1407518367/I2WQKcwoZ?type=comment"
    # a = 'https://m.weibo.cn/status/I4ORKgkPA?'
    # a = 'http://weibo.com/6439202659/IdJ0N29kZ'
    # a = 'https://weibo.com/2001779053/IeMy8EVqp?ref=home&rid=0_0_8_4726927301076592586_0_0_0&type=comment'
    # a = 'https://weibo.com/2002148123/Iet2s6dTy#99c2e3860ce4ff10cc941057706f2b28'
    # g = Get_weiboID()
    # print(g.get_bid(a))
    # print(g.run(a))
    # print(Utils.process_timestamp(str(1576060544000)))
    # print(Utils.md5_encrypt('11eyJpdiI6IlRVSlEzYlNEMG9GS2JieGtyTG1GZHc9PSIsInZhbHVlIjoiXC9vdmw3MDIwNmwwa29XMFhjMncwR0FkUXhqaGl1TEVSb05CT3JxcDZzdjF0bG1odVBkVEdiWnpkMWNrU292b3Q5RWwwOVFSRVRMTVV4cjNDSlEzMG9VQXRZcVBYT040WjZqQitjTDZIRFhBPSIsIm1hYyI6IjA1ZjYzMDNmYmZiZWI3ZTBiYjBjNGUwNDNlZjUzNWMyNzllNzA1ZDBjNTljNzNlNGE5MjAzZjcxMDUzMTZmZTAifQ=='))
    b = 'eyJhbGciOiJIUzUxMiJ9.eyJ0b2tlbiI6ImU4MjNmZWJmMzM2NjZjNTc4ZTllODU0NmE5YWU0ZjdkNjQxMDFjMDEifQ'
    print(Utils.hmac_sha512(b,'Ve1BakMFZPKBejt6gdA2-2020-04-08'))
